import {getParams, getWindowDate, renderAntTreeSelectData} from "@/utils";
import {asyncFocusService} from "@/api/approve/approve";
import {message} from 'ant-design-vue';

const EditCell = {
    name: 'EditCell',
    inject: {
        connectStore: {
            default: () => ({})
        }
    },
    props: {
        record: {
            type: Object,
            default: () => ({})
        },
        title: {
            type: String,
            default: () => ''
        },
        edit: {
            type: Boolean,
            default: () => false
        },
        value: {
            type: [String, Number, Boolean],
            default: () => ''
        },
        focusUrl: {
            type: String,
            default: () => ''
        },
        columnSelectOptions: {
            type: [Object, Array, undefined],
            default: () => undefined
        },
        componentType: {
            type: String,
            default: () => ''
        },
        isRules: {
            type: Boolean,
            default: () => false
        },
        isNumber: {
            type: Boolean,
            default: () => false
        },
        dataIndex: {
            type: String,
            default: () => ''
        },
        selectViewOptions: {
            type: Object,
            default: () => ({})
        },
        isUrlSpecial: {
            type: Boolean,
            default: () => false
        },
        showSearch: {
            type: [Boolean, String, Number],
            default: () => false
        },
    },
    data() {
        return {
            editTable: false,
            editTableCellSelectOptions: [],
            editValue: this.value
        }
    },
    methods: {
        async editTableCellToggleEdit(disabled) {
            this.$nextTick(() => {
                this.editTable = disabled ? disabled : !this.editTable
                if (!this.editTable) {
                    this.editValue = this.value;
                }
            })
        },
        async editTableSetEditTableEmptyData(label) {
            const cellIndex = this.TableContext.editTableEmptyData.findIndex(item => this.record.RN === item.RN.value)
            this.TableContext.editTableEmptyData[cellIndex][this.dataIndex] = {
                ...this.TableContext.editTableEmptyData[cellIndex][this.dataIndex],
                ...label
            }
        }
    },
    computed: {
        TableContext() {
            return this.connectStore.value.TableContext;
        },
        AdminLayout() {
            return this.connectStore.value.AdminLayout
        }
    },
    render() {
        const {
            componentType,
            title,
            edit,
            isNumber,
            record,
            value,
            dataIndex,
            selectViewOptions,
            columnSelectOptions,
            focusUrl,
            isRules,
            isUrlSpecial,
            showSearch
        } = this.$props;

        const {handleSave} = this.TableContext;
        let childNode = this.editValue;
        const editTableCellValidateSave = async (label) => {
            const {economySectiongovName, economySectiongovCode, functionSectionCode, isLeafs, divisionGuid, divisionName} = (label)
            if (dataIndex === 'functionSectionText') {
                if (functionSectionCode)
                    if (Object.prototype.toString.call(functionSectionCode) === '[object String]' && Number(isLeafs) !== 1) {
                        message.warning('改要素不是最底级,请联系管理员.')
                        return;
                    }
            }
            if (dataIndex === 'enterpriseText') {
                if (divisionGuid === '' || divisionName === '') {
                    message.warning('调整后的单位未绑定科室，请联系信息科修改基础资料.');
                    this.editValue = ''
                    return;
                }
            }
            let sum = 0

            const editTableJudgmentIndex = this.TableContext.editTableJudgementAmount.findIndex(item => item.budgetId === record.budgetId)
            try {
                if (dataIndex === 'economySectionText') {
                    record.ecoGovText = economySectiongovCode + ' ' + economySectiongovName
                }
                if (dataIndex === 'programName' && decodeURIComponent(getParams().title) === '项目调整') {
                    record.programTypeName = label.programtypename;
                }

                if (isRules) {
                    if (this.TableContext.isEditTableComponent) {
                        let originMoney = 0
                        const editTableJudgementAmount = this.TableContext.detailAdjustmentData.filter(item => item.detailId === record.detailId && item.budgetType);
                        const editTableOriginTable = this.TableContext.detailAdjustmentData.filter(item => item.detailId === record.detailId && !item.budgetType);

                        editTableOriginTable.forEach(item => {
                            originMoney += item.bMoney;
                        });

                        originMoney = !originMoney ? this.editValue : originMoney - record.bMoney + this.editValue;

                        if (originMoney > editTableJudgementAmount[0].bMoney) {
                            message.warning('输入值不能大于总值');
                            await handleSave({...record, [dataIndex]: this.editValue, bMoney: 0});
                            await this.editTableCellToggleEdit();
                            await this.editTableSetEditTableEmptyData(label);
                            return;
                        }
                        await handleSave({...record, [dataIndex]: this.editValue})
                        const onlySumTable = this.TableContext.detailAdjustmentData.filter(item => item.budgetId === record.budgetId && !item.budgetType)
                        await onlySumTable.forEach(item => {
                            sum += Number(item[dataIndex]);
                        });
                        if (originMoney > editTableJudgementAmount[0].bMoney) {
                            message.warning('输入金额不能大于可调整金额')
                            await handleSave({...record, [dataIndex]: this.editValue, bMoney: 0})
                        } else {
                            await handleSave({...record, [dataIndex]: this.editValue})
                            if (this.TableContext.editTableJudgementAmount[editTableJudgmentIndex]) {
                                this.TableContext.editTableJudgementAmount[editTableJudgmentIndex].bMoney = Number((editTableJudgementAmount[0].bMoney - Number(sum)).toFixed(2))
                            }
                        }
                    }
                } else {
                    await handleSave({...record, [dataIndex]: this.editValue})
                }
                await this.editTableCellToggleEdit()
                await this.editTableSetEditTableEmptyData(label)
            } catch (e) {
                Promise.reject(e)
            }
        }

        const editTableCellHandleSelectChange = async (title, value, label) => {
            await editTableCellValidateSave(label)
        }

        const handleSelectFocus = async (componentType) => {
            if (this.editTableCellSelectOptions && this.editTableCellSelectOptions.length > 0) return;
            let selectOptions;
            if (columnSelectOptions) {
                selectOptions = columnSelectOptions;
                this.editTableCellSelectOptions = selectOptions;
            } else {
                const {renderKey, renderValue} = selectViewOptions;
                asyncFocusService(focusUrl,
                    dataIndex === 'programName'
                        ?
                        {
                            year: getWindowDate().year,
                            isLocal: false,
                            enterpriseGuid: this.TableContext.enterpriseGuid || record.enterpriseGuid,
                            status: 1,
                            programTypeCode: getParams().programTypeCode || ''
                        }
                        :
                        isUrlSpecial
                            ?
                            {
                                year: getWindowDate().year,
                                type: dataIndex,
                                sId: getParams().sId
                            }
                            :
                            this.TableContext.flag
                                ?
                                {
                                    ...this.TableContext.focusData,
                                    enterpriseKind: record.enterpriseKind
                                }
                                :
                                {
                                    ...this.TableContext.focusData
                                }
                ).then(async res => {
                    const {success, data} = res
                    if (success) {
                        if (componentType === 'select') {
                            selectOptions = data;
                        } else if (componentType === 'treeSelect') {
                            selectOptions = renderAntTreeSelectData(data, renderValue, renderKey, true);
                        }
                        this.editTableCellSelectOptions = selectOptions;
                    }
                })
            }
        }

        const renderEditTableCellChildNodeSelect = () => {
            return (
                <a-select
                    showSearch={!!showSearch}
                    vModel={this.editValue}
                    onChange={(value, label) => editTableCellHandleSelectChange(title, value, label.data)}
                    onFocus={() => handleSelectFocus(componentType)}
                    onBlur={async () => this.editTableCellToggleEdit}
                    placeholder={`请选择${title}`}
                    dropdownStyle={{
                        width: 'auto',
                        maxHeight: '350px'
                    }}
                >
                    {
                        this.editTableCellSelectOptions.length && this.editTableCellSelectOptions.map((option, index) => {
                            const renderOptionsKey = {}
                            for (const i in option) {
                                if (Object.prototype.hasOwnProperty.call(option, i)) {
                                    renderOptionsKey[`${i.toLowerCase()}`] = option[i]
                                }
                            }
                            return (
                                <a-select-option
                                    {...{...renderOptionsKey}}
                                    key={selectViewOptions ? option[selectViewOptions.renderMapKey] : index}
                                    value={
                                        selectViewOptions
                                            ?
                                            selectViewOptions.renderValue === selectViewOptions.renderKey
                                                ?
                                                option[selectViewOptions.renderValue]
                                                :
                                                option[selectViewOptions.renderKey]
                                            :
                                            option.id
                                    }
                                >
                                    {
                                        selectViewOptions ? option[selectViewOptions.renderValue] : option.value
                                    }
                                </a-select-option>
                            )
                        })
                    }
                </a-select>
            )
        }

        const renderEditTableCellChildNodeTreeSelect = () => {
            return (
                <a-tree-select
                    showSearch={!!showSearch}
                    vModel={this.editValue}
                    onChange={async (value, label, extra) => {
                        const {triggerNode} = extra
                        const {dataRef: props} = triggerNode;
                        this.TableContext.crossUnit();
                        await editTableCellHandleSelectChange(title, value, props)
                    }}
                    placeholder={`请选择${title}`}
                    dropdownStyle={{
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                        overflow: 'auto',
                        maxHeight: '350px',
                    }}
                    treeData={this.editTableCellSelectOptions}
                    onFocus={() => handleSelectFocus(componentType)}
                />
            )
        }

        const renderEditTableCellChildNodeInput = () => {
            return (
                isNumber
                    ?
                    (
                        <a-input-number
                            vModel={this.editValue}
                            min={0.01}
                            placeholder={`请输入${title}`}
                            onBlur={async (e) => {
                                await editTableCellValidateSave({
                                    value: e.target.value
                                })
                            }}
                            onPressEnter={async (e) => {
                                await editTableCellValidateSave({
                                    value: e.target.value
                                })
                                await this.editTableCellToggleEdit()
                            }}
                        />
                    )
                    :
                    (
                        <a-input
                            vModel={this.editValue}
                            placeholder={`请输入${title}`}
                            onBlur={async (e) => {
                                await editTableCellValidateSave({
                                    value: e.target.value
                                })
                            }}
                            onPressEnter={async (e) => {
                                await editTableCellValidateSave({
                                    value: e.target.value
                                })
                                await this.editTableCellToggleEdit()
                            }}
                        />
                    )
            )
        }

        const renderEditTableCellChildNode = () => {
            if (this.editTable) {
                if (componentType === 'select') {
                    childNode = renderEditTableCellChildNodeSelect()
                } else if (componentType === 'treeSelect') {
                    childNode = renderEditTableCellChildNodeTreeSelect()
                } else {
                    childNode = renderEditTableCellChildNodeInput()
                }
            } else {
                childNode = title === '政府经济科目'
                    ?
                    (
                        <div title={this.editValue}>
                            {this.value}
                        </div>
                    )
                    :
                    title === '采购目录'
                        ?
                        Number(record.isBuy) === 1 || record.isBuy === '是'
                            ?
                            (
                                <div class='editTableRow' title={this.editValue} onClick={this.editTableCellToggleEdit}>
                                    {value}
                                </div>
                            )
                            :
                            (
                                <div title={this.editValue}>
                                    {this.value}
                                </div>
                            )
                        :
                        <div class='editTableRow' title={this.editValue} onClick={this.editTableCellToggleEdit}>
                            {this.value}
                        </div>
            }
        }

        if (edit && (!this.TableContext.flag || Number(this.TableContext.flag) !== 1)) {
            if (this.TableContext.isEditTableComponent) {
                if (!record.budgetType) {
                    renderEditTableCellChildNode()
                }
            } else {
                renderEditTableCellChildNode()
            }
        }
        return (
            <div class='editTableOriginRow' title={this.editValue}
                 onmouseenter={() => this.editTableCellToggleEdit(true)}>
                {childNode}
            </div>
        )
    }
};

export default EditCell;
